/*
 * QRCodeReaderViewController
 *
 * Copyright 2014-present Yannick Loriot.
 * http://yannickloriot.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#import "QRCodeReaderViewController.h"
#import "QRCameraSwitchButton.h"
#import "QRCodeReaderView.h"
#import "ZJAdditions.h"
#import "YJProgressHUD.h"
#import "CustomLabel.h"
#import "NetWorkingManager.h"
#import "TextViewController.h"
#import "WebViewController.h"


#define mainHeight     [[UIScreen mainScreen] bounds].size.height
#define mainWidth      [[UIScreen mainScreen] bounds].size.width
#define navBarHeight   self.navigationController.navigationBar.frame.size.height

@interface QRCodeReaderViewController () <AVCaptureMetadataOutputObjectsDelegate,QRCodeReaderViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{

    NSString * _type;
    
}
@property (strong, nonatomic) QRCameraSwitchButton *switchCameraButton;
@property (strong, nonatomic) QRCodeReaderView     *cameraView;
@property (strong, nonatomic) AVAudioPlayer        *beepPlayer;
@property (strong, nonatomic) UIButton             *cancelButton;
@property (strong, nonatomic) UIImageView          *imgLine;
@property (strong, nonatomic) UILabel              *lblTip;
@property (strong, nonatomic) NSTimer              *timerScan;

@property (strong, nonatomic) AVCaptureDevice            *defaultDevice;
@property (strong, nonatomic) AVCaptureDeviceInput       *defaultDeviceInput;
@property (strong, nonatomic) AVCaptureDevice            *frontDevice;
@property (strong, nonatomic) AVCaptureDeviceInput       *frontDeviceInput;
@property (strong, nonatomic) AVCaptureMetadataOutput    *metadataOutput;
@property (strong, nonatomic) AVCaptureSession           *session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;

@property (strong, nonatomic) CIDetector *detector;

@property (copy, nonatomic) void (^completionBlock) (NSString *);
@property (copy, nonatomic) void (^login) (BOOL );
@property (copy, nonatomic) void (^sign) (NSDictionary *);
/**  提示语  */
@property (strong, nonatomic) UILabel  *markLabel;
@end

@implementation QRCodeReaderViewController



- (id)init
{
    
    NSString * wavPath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"wav"];
    NSData* data = [[NSData alloc] initWithContentsOfFile:wavPath];
    _beepPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
    
    return [self initWithCancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")];
}

- (id)initWithCancelButtonTitle:(NSString *)cancelTitle
{
    if ((self = [super init])) {
        self.view.backgroundColor = [UIColor clearColor];

        [self setupAVComponents];
        [self configureDefaultComponents];
        [self setupUIComponentsWithCancelButtonTitle:cancelTitle];
        [self setupAutoLayoutConstraints];

        [_cameraView.layer insertSublayer:self.previewLayer atIndex:0];
        
    }
    return self;
}

+ (instancetype)readerWithCancelButtonTitle:(NSString *)cancelTitle
{
  return [[self alloc] initWithCancelButtonTitle:cancelTitle];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:230/20.0 green:57.0/255.0  blue:85.0/255.0  alpha:1.0];
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.titlelabel.text = @"扫描二维码";
//    self.titlelabel.textColor = [UIColor whiteColor];
//    self.navigView.backgroundColor = [UIColor themeColor];
//    [self.leftButton setImage:[UIImage LoadImageWithPathImageName:@"icon_jiantou2" ofType:nil] forState:UIControlStateNormal];
   
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self startScanning];
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请在iPhone的\"设置－隐私－相机\"选项中,允许\"浦东i党建\"访问你的相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
  [self stopScanning];
    
  [super viewWillDisappear:animated];
}

- (void)viewWillLayoutSubviews
{
  [super viewWillLayoutSubviews];
  
  _previewLayer.frame = self.view.bounds;
}

- (BOOL)shouldAutorotate
{
  return YES;
}

- (void)scanAnimate
{
    _imgLine.frame = CGRectMake(49, _cameraView.innerViewRect.origin.y, mainWidth - 49 * 2, 3);
    [UIView animateWithDuration:2 animations:^{
        _imgLine.frame = CGRectMake(_imgLine.frame.origin.x, _imgLine.frame.origin.y + _cameraView.innerViewRect.size.height - 6, _imgLine.frame.size.width, _imgLine.frame.size.height);
    }];
}

- (void)loadView:(CGRect)rect
{
    _imgLine.frame = CGRectMake(0, _cameraView.innerViewRect.origin.y, mainWidth, 12);
    [self scanAnimate];
}

#pragma mark - Managing the Orientation

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
  [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  
  [_cameraView setNeedsDisplay];
  
  if (self.previewLayer.connection.isVideoOrientationSupported) {
    self.previewLayer.connection.videoOrientation = [[self class] videoOrientationFromInterfaceOrientation:toInterfaceOrientation];
  }
}

+ (AVCaptureVideoOrientation)videoOrientationFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  switch (interfaceOrientation) {
    case UIInterfaceOrientationLandscapeLeft:
      return AVCaptureVideoOrientationLandscapeLeft;
    case UIInterfaceOrientationLandscapeRight:
      return AVCaptureVideoOrientationLandscapeRight;
    case UIInterfaceOrientationPortrait:
      return AVCaptureVideoOrientationPortrait;
    default:
      return AVCaptureVideoOrientationPortraitUpsideDown;
  }
}

#pragma mark - Managing the Block

- (void)setCompletionWithBlock:(void (^) (NSString *resultAsString))completionBlock login:(void (^)(BOOL))login sign:(void (^)(NSDictionary *))sign
{
    self.login = login;
    self.sign = sign;
    self.completionBlock = completionBlock;
}

- (void)setCompletionWithBlock:(void (^)(NSString *))completionBlock{
    [self setCompletionWithBlock:completionBlock login:nil sign:nil ];
}


#pragma mark - Initializing the AV Components

- (void)setupUIComponentsWithCancelButtonTitle:(NSString *)cancelButtonTitle
{
    self.cameraView                                       = [[QRCodeReaderView alloc] init];
    _cameraView.translatesAutoresizingMaskIntoConstraints = NO;
    _cameraView.clipsToBounds                             = YES;
    _cameraView.delegate                                  = self;
    [self.view addSubview:_cameraView];
    [self.view bringSubviewToFront:self.navigView];
    if (_frontDevice) {
        _switchCameraButton = [[QRCameraSwitchButton alloc] init];
        [_switchCameraButton setTranslatesAutoresizingMaskIntoConstraints:false];
        [_switchCameraButton addTarget:self action:@selector(switchCameraAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_switchCameraButton];
    }

    self.cancelButton                                       = [[UIButton alloc] init];
    self.cancelButton.hidden                                = YES;
    _cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [_cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    self.switchCameraButton.hidden = YES;
    
    CGFloat c_width = mainWidth - 100;
    CGFloat s_height = mainHeight - 40;
    CGFloat y = (s_height - c_width) / 2 - s_height / 6;
    
    _lblTip = [[CustomLabel alloc] initWithFrame:CGRectMake(0,y + 90 + c_width, mainWidth, 70)];
    _lblTip.numberOfLines = 0;
    _lblTip.textColor = [UIColor whiteColor];
    _lblTip.font = [UIFont systemFontOfSize:13];
    _lblTip.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_lblTip];

    CGFloat corWidth = 16;
    
    UIImageView* img1 = [[UIImageView alloc] initWithFrame:CGRectMake(49, y + 76, corWidth, corWidth)];
    img1.image = [UIImage imageNamed:@"cor1"];
    [self.view addSubview:img1];
    
    UIImageView* img2 = [[UIImageView alloc] initWithFrame:CGRectMake(35 + c_width, y + 76, corWidth, corWidth)];
    img2.image = [UIImage imageNamed:@"cor2"];
    [self.view addSubview:img2];
    
    UIImageView* img3 = [[UIImageView alloc] initWithFrame:CGRectMake(49, y + c_width + 64, corWidth, corWidth)];
    img3.image = [UIImage imageNamed:@"cor3"];
    [self.view addSubview:img3];
    
    UIImageView* img4 = [[UIImageView alloc] initWithFrame:CGRectMake(35 + c_width, y + c_width + 64, corWidth, corWidth)];
    img4.image = [UIImage imageNamed:@"cor4"];
    [self.view addSubview:img4];
    
    
    _imgLine = [[UIImageView alloc] init];
    _imgLine.image = [UIImage imageNamed:@"blueline"];
    [self.view addSubview:_imgLine];
    
    [self.view addSubview:self.markLabel];
    [self.view bringSubviewToFront:self.markLabel];
    self.markLabel.sd_layout
    .bottomSpaceToView(self.view,130 * [UIScreen zj_screenHScale])
    .centerXEqualToView(self.view)
    .widthIs(self.view.width)
    .heightIs(20 * [UIScreen zj_screenHScale]);

}

- (void)setupAutoLayoutConstraints
{
  NSDictionary *views = NSDictionaryOfVariableBindings(_cameraView, _cancelButton);
  
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_cameraView][_cancelButton(0)]|" options:0 metrics:nil views:views]];
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_cameraView]|" options:0 metrics:nil views:views]];
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_cancelButton]-|" options:0 metrics:nil views:views]];
  
  if (_switchCameraButton) {
    NSDictionary *switchViews = NSDictionaryOfVariableBindings(_switchCameraButton);
    
    [self.view addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_switchCameraButton(50)]" options:0 metrics:nil views:switchViews]];
    [self.view addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:[_switchCameraButton(70)]|" options:0 metrics:nil views:switchViews]];
  }
}

- (void)setupAVComponents
{
  self.defaultDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  
  if (_defaultDevice) {
    self.defaultDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_defaultDevice error:nil];
    self.metadataOutput     = [[AVCaptureMetadataOutput alloc] init];
    self.session            = [[AVCaptureSession alloc] init];
    self.previewLayer       = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    
    for (AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
      if (device.position == AVCaptureDevicePositionFront) {
        self.frontDevice = device;
      }
    }
    
    if (_frontDevice) {
      self.frontDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_frontDevice error:nil];
    }
  }
}

- (void)configureDefaultComponents
{
  [_session addOutput:_metadataOutput];
  
  if (_defaultDeviceInput) {
    [_session addInput:_defaultDeviceInput];
  }
  
  [_metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  if ([[_metadataOutput availableMetadataObjectTypes] containsObject:AVMetadataObjectTypeQRCode]) {
    [_metadataOutput setMetadataObjectTypes:@[ AVMetadataObjectTypeQRCode ]];
  }
  [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
  [_previewLayer setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
  
  if ([_previewLayer.connection isVideoOrientationSupported]) {
    
      _previewLayer.connection.videoOrientation = [[self class] videoOrientationFromInterfaceOrientation:self.interfaceOrientation];
    
  }
}

- (void)switchDeviceInput
{
  if (_frontDeviceInput) {
    [_session beginConfiguration];
    
    AVCaptureDeviceInput *currentInput = [_session.inputs firstObject];
    [_session removeInput:currentInput];
    
    AVCaptureDeviceInput *newDeviceInput = (currentInput.device.position == AVCaptureDevicePositionFront) ? _defaultDeviceInput : _frontDeviceInput;
    [_session addInput:newDeviceInput];
    
    [_session commitConfiguration];
  }
}

#pragma mark - Catching Button Events

- (void)cancelAction:(UIButton *)button
{
  [self stopScanning];
  
  if (_completionBlock) {
    _completionBlock(nil);
  }
  
  if (_delegate && [_delegate respondsToSelector:@selector(readerDidCancel:)]) {
    [_delegate readerDidCancel:self];
  }
}

- (void)switchCameraAction:(UIButton *)button
{
  [self switchDeviceInput];
}

#pragma mark - Controlling Reader

- (void)startScanning;
{
    if (![self.session isRunning]) {
             [self.session startRunning];
    }
    
    if(_timerScan)
    {
        [_timerScan invalidate];
        _timerScan = nil;
    }
    
    _timerScan = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scanAnimate) userInfo:nil repeats:YES];
}

- (void)stopScanning;
{
    if ([self.session isRunning]) {
        
        [self.session stopRunning];
    }
    if(_timerScan)
    {
        [_timerScan invalidate];
        _timerScan = nil;
    }
}

#pragma mark - AVCaptureMetadataOutputObjects Delegate Methods
/**  扫描成功的返回二维码信息  */
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    
    
    for(AVMetadataObject *current in metadataObjects) {
        if ([current isKindOfClass:[AVMetadataMachineReadableCodeObject class]]
            && [current.type isEqualToString:AVMetadataObjectTypeQRCode])
        {
            NSString *scannedResult = [(AVMetadataMachineReadableCodeObject *) current stringValue];

            [self stopScanning];

            if (_completionBlock) {
                [_beepPlayer play];
                _completionBlock(scannedResult);
            }
            //            if (_delegate && [_delegate respondsToSelector:@selector(reader:didScanResult:)]) {
            //                [_delegate reader:self didScanResult:scannedResult];
            //            }
            
#pragma mark - 添加方法
            
            [self QRcodeMessage:scannedResult];
            
          

            break;
        }
    }
}



#pragma mark - 得到二维码信息后的操作

- (void)QRcodeMessage:(NSString *)message{
    //1、判断字符串前面是否是 http
    NSString *http = [message substringToIndex:4];
    if (![http isEqualToString:@"http"]) {//如果不是http，直接跳textView页面
        TextViewController *vc = [[TextViewController alloc]init];
        vc.text = message;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    //2、包含 http，再判断是否包含 @“code”
    if ([message rangeOfString:@"code="].location == NSNotFound && [message rangeOfString:@"aid="].location == NSNotFound) {//包含http但是没包含code、aid，直接跳webView页面

        WebViewController *vc = [[WebViewController alloc]init];
        vc.url = message;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    //登录
    if (([message rangeOfString:@"code="].location != NSNotFound) && ([message rangeOfString:@"type="].location != NSNotFound)) {
    //3、包含 http与code，用code对于的字符串 进行网络请求
    NSRange codeRange = [message rangeOfString:@"code="]; //现获取要截取的字符串位置
    NSRange typeRange = [message rangeOfString:@"&type="]; //现获取要截取的字符串位置
    
    NSString * code = [message substringWithRange:NSMakeRange(codeRange.location + codeRange.length, typeRange.location - codeRange.location - codeRange.length)]; //截取字符串
    NSString * type = [message substringFromIndex:typeRange.location + typeRange.length]; //截取字符串
    [self getQRCodeInfoWithCode:code type:type];
    }
    //活动签到
    if (([message rangeOfString:@"aid="].location != NSNotFound) && ([message rangeOfString:@"type="].location != NSNotFound)) {
        //3、包含 http与code，用code对于的字符串 进行网络请求
        NSRange codeRange = [message rangeOfString:@"aid="]; //现获取要截取的字符串位置
        NSRange typeRange = [message rangeOfString:@"&type="]; //现获取要截取的字符串位置
        
        NSString * code = [message substringWithRange:NSMakeRange(codeRange.location + codeRange.length, typeRange.location - codeRange.location - codeRange.length)]; //截取字符串
        NSString * type = [message substringFromIndex:typeRange.location + typeRange.length]; //截取字符串
        [self getQRCodeInfoWithCode:code type:type];
    }
}
//查询服务器
- (void)getQRCodeInfoWithCode:(NSString *)code  type:(NSString *)type{
    
    __weak typeof(self) weakSelf = self;
    if ([type isEqualToString:@"login"]) {//验证登录
        [weakSelf login_codeID:code];
    }else if ([type isEqualToString:@"sign"]){//活动签到
        [weakSelf activity_sign_ID:code];
    }
}
#pragma mark - 二维码__登录
//登录
- (void)login_codeID:(NSString *)code{
    [YJProgressHUD show:@"登录验证中..." inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
 //1、获取验证码
    [self getMobleCodeSuccess:^(NSString *MOBILE_CODE) {
        //2、拿到验证码进行网络请求
        [weakSelf netLogin_code:code mobile_code:MOBILE_CODE];
    }];
}

//获取验证码（不发送到手机）
- (void)getMobleCodeSuccess:(void(^)(NSString * MOBILE_CODE))success{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"MOBILE":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.MOBILE,
                           @"CODE_SOURCE":@"login"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getMobileCode] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"30000"]) {//验证码获取成功
            success([object objectForKey:@"CODE"]);
        }else{
        [weakSelf verificationFailure_string:@"验证失败"];
            if (weakSelf.login) {
                weakSelf.login(NO);
            }
            
        }
    } Fail:^(id object) {
        [weakSelf verificationFailure_string:@"验证失败"];
        if (weakSelf.login) {
            weakSelf.login(NO);
        }
    }];
}
//进行网络请求 (code:二维码id   mobile_code：验证码)
- (void)netLogin_code:(NSString *)code mobile_code:(NSString *)mobile_code{
    /*"CODE":CODE,
     "VALUE":"#"+{"MOBILE": "10000000005",
	    "MOBILE_CODE":mo_code}
     
     CODE 二维码ID
     MOBILE 用户电话号码
     MOBILE_CODE 验证码*/
    __weak typeof(self) weakSelf = self;
    NSDictionary *VALUE = @{@"MOBILE":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.MOBILE,
                            @"MOBILE_CODE":mobile_code};
    NSDictionary *dict = @{@"CODE":code,
                           @"VALUE":[NSString stringWithFormat:@"#%@",[VALUE yy_modelToJSONString]]};
    [NetWorkingManager postWithUrlString:[NetWorkingURL AddUserMeg] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            [weakSelf verificationSuccess_string:@"验证成功"];
            if (weakSelf.login) {
                weakSelf.login(YES);
            }
        }else{
            [weakSelf verificationFailure_string:@"验证失败"];
            if (weakSelf.login) {
                weakSelf.login(NO);
            }
        }
    } Fail:^(id object) {
            [weakSelf verificationFailure_string:@"验证失败"];
        if (weakSelf.login) {
            weakSelf.login(NO);
        }
    }];
    
}

#pragma mark - 二维码__活动签到
- (void)activity_sign_ID:(NSString *)ID{
    [YJProgressHUD show:@"活动签到中..." inView:self.view mode:YJProgressModeLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"AI_ID":ID,
                           @"USER_ID":[ZJUserInfoModel sharedUserInfo].USER_MODEL_BOOK.ID? [ZJUserInfoModel sharedUserInfo].USER_MODEL_BOOK.ID :@"",
                           @"TYPE":@"0",
                           @"LNG": @"",
                           @"LAT": @"",
                           @"ADDR": @"",
                           @"MEMBERID": ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID,
                           @"DEPTID": ZJUSERINFORMODEL.DEPT_MODEL_BOOK.ID ? ZJUSERINFORMODEL.DEPT_MODEL_BOOK.ID:@""};
    [NetWorkingManager postWithUrlString:[NetWorkingURL mobileSignIn] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            [weakSelf verificationSuccess_string:@"签到成功"];
            
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
            
        }else if([model.STATE isEqualToString:@"80001"]){
            [weakSelf verificationFailure_string:@"重复签到"];
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
        }else if([model.STATE isEqualToString:@"80011"]){
            [weakSelf verificationFailure_string:@"你还未参加活动，请先报名"];
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
        }else if([model.STATE isEqualToString:@"80004"]){
            [weakSelf verificationFailure_string:@"无此活动或已被删除"];
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
        }else if([model.STATE isEqualToString:@"80002"]){
            [weakSelf verificationFailure_string:@"活动已结束"];
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
        }else{
            [weakSelf verificationFailure_string:@"签到失败"];
            if (weakSelf.sign) {
                weakSelf.sign(object);
            }
        }
        
        
    } Fail:^(id object) {
        [weakSelf verificationFailure_string:@"签到失败"];
        if (weakSelf.sign) {
            weakSelf.sign(@{@"STATE": @"20001"});
        }
        
    }];
}


- (void)verificationSuccess_string:(NSString *)string{
    [YJProgressHUD show:string inView:self.view mode:YJProgressModeSuccess];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [YJProgressHUD hide];
        [self.navigationController popViewControllerAnimated:YES];
    });

}
- (void)verificationFailure_string:(NSString *)string{
    [YJProgressHUD show:string inView:self.view mode:YJProgressModeSuccess];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [YJProgressHUD hide];
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (NSString *)jsonStringFromObject:(id)object { //OC对象转JSON
    NSError *erro = nil;
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&erro];
    NSString *jsonString = [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];
    return jsonString;
}

#pragma mark - Checking the Metadata Items Types

+ (BOOL)isAvailable
{
  @autoreleasepool {
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if (!captureDevice) {
      return NO;
    }
    
    NSError *error;
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!deviceInput || error) {
      return NO;
    }
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    if (![output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
      return NO;
    }
    
    return YES;
  }
}

#pragma mark - Checking RightBarButtonItem
-(void)clickRightBarButton:(UIBarButtonItem*)item
{
    self.detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- ( void )imagePickerController:( UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
       NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    if (features.count >=1) {
        CIQRCodeFeature *feature = [features objectAtIndex:0];
        NSString *scannedResult = feature.messageString;
        if (_completionBlock) {
            [_beepPlayer play];
            _completionBlock(scannedResult);
        }
        
        if (_delegate && [_delegate respondsToSelector:@selector(reader:didScanResult:)]) {
            [_delegate reader:self didScanResult:scannedResult];
        }
    }
}





- (void)HintString:(NSString *)string  Type:(NSString *)type{
    _lblTip.text = string;
    _type = type;
}


- (UILabel *)markLabel{
    if (!_markLabel) {
        _markLabel = ({
            UILabel *label = [UILabel new];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.backgroundColor = [UIColor clearColor];
            label.font = [UIFont systemFontOfSize:17 * [UIScreen zj_textFontScale]];
            label.text = @"请将二维码放在方框以内，以便于扫描";
            label;
        });
    }
    return _markLabel;
}


@end
